package com.famnote.randomchat;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;

import com.famnote.randomchat.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener 
{
 
	// Debugging
    private static final String TAG = "LoginActivity";
    private static final boolean D = true;
    
    
    private ProgressDialog dialog;
    
	Button mLogin;
	Button mRegister;
 
	EditText muname;
	EditText mpassword;
 
	DBHelper DB = null;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
    
        mRegister = (Button)findViewById(R.id.register);
        mRegister.setOnClickListener(this);
        
        mLogin = (Button)findViewById(R.id.login);
        mLogin.setOnClickListener(this); 
        
    }


    public void onClick(View v) 
    {
    	switch(v.getId())
    	{
 
    		case R.id.register:
    			Intent i = new Intent(getBaseContext(), Registration.class);
    			startActivity(i);
    			break;
  
    		case R.id.login:
  
    			muname = (EditText)findViewById(R.id.Ledituname);
    			mpassword = (EditText)findViewById(R.id.Leditpw);
  
    			String username = muname.getText().toString();
    			String password = mpassword.getText().toString();
  
  
  
    			if(username.equals("") || username == null)
    			{
    				Toast.makeText(getApplicationContext(), "Please enter User Name", Toast.LENGTH_SHORT).show();
    			}
    			else if(password.equals("") || password == null)
    			{
    				Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();
    			}
    			else
    			{
    				/*
    				boolean validLogin = validateLogin(username, password, getBaseContext());
    				if(validLogin)
    				{
    					//System.out.println("In Valid");
    					Intent in = new Intent(getBaseContext(), Welcome1.class);
    					in.putExtra("UserName", muname.getText().toString());
    					startActivity(in);
    					//finish();
    				}
    				*/
    				
    				String msg = getResources().getString(R.string.loading);
    		        dialog = ProgressDialog.show(this, "", msg, true);
    		        
    				// Creating a new non-ui thread task to download xml data 
    		        ProcessXmppTask processXmppTask = new ProcessXmppTask();
                    // Starting the download process
                    processXmppTask.execute(username, password);
                    
    			}
    			break;
 
    	}
  
    }


    private boolean validateLogin(String username, String password, Context baseContext) 
    {
    	
    	DB = new DBHelper(getBaseContext());
    	SQLiteDatabase db = DB.getReadableDatabase();
  
    	String[] columns = {"_id"};
  
    	String selection = "username=? AND password=?";
    	String[] selectionArgs = {username,password};
  
    	Cursor cursor = null;
    	try{
  
    		cursor = db.query(DBHelper.DATABASE_TABLE_NAME, columns, selection, selectionArgs, null, null, null);
    		startManagingCursor(cursor);
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	int numberOfRows = cursor.getCount();
  
    	if(numberOfRows <= 0)
    	{
  
    		Toast.makeText(getApplicationContext(), "User Name and Password miss match..\nPlease Try Again", Toast.LENGTH_LONG).show();
    		Intent intent = new Intent(getBaseContext(), LoginActivity.class);
    		startActivity(intent);
    		return false;
    	}
  		
    	return true;  
    }
 
 
    public void onDestroy()
    {
    	super.onDestroy();
    	
    	if (DB != null)
    	{
    		DB.close();
    	}
    }
    
    
    
    private class ProcessXmppTask extends AsyncTask<String, Integer, String> {
    	
    	String result = null;
    	
    	@Override
    	protected String doInBackground(String... args) {

    		
    		String username = args[0];
    		String password = args[1];
  
    		if(D) Log.e(TAG, "++ XMPP connect ++");
	        
			ConnectionConfiguration connConfig =
	        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
	        //connConfig.setSASLAuthenticationEnabled(true);
	        //connConfig.setDebuggerEnabled(true);

	        XMPPConnection connection = new XMPPConnection(connConfig);
	        

	        if(D) Log.e(TAG, "++ connection.connect() ++");
	        
	        try {
	            connection.connect();
	            
	            if(D) Log.e(TAG, "++ after connection.connect() ++");

	            //connection.loginAnonymously();
	            
	            connection.login(username, password);
	            
	            //Log.i("XMPPClient", "Logged in as " + connection.getUser());
	            //if(D) Log.e(TAG, "++ connection.loginAnonymously() ++");
	            
	            
	            /*
	        	if (mRoomid != null) {
	                String room = mRoomid + "@conference.push.appaas.com";
	                MultiUserChat muc = new MultiUserChat(connection, room);
	                muc.join(connection.getUser());
	               
	        	}
	        	*/
	            
	            /*
	            ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
	            if (sdm == null) sdm = new ServiceDiscoveryManager(connection);    
	            sdm.addFeature("http://jabber.org/protocol/disco#info");
	            sdm.addFeature("jabber:iq:privacy");
	            
	            configure();
	            
	            
	            Collection<HostedRoom> rooms = MultiUserChat.getHostedRooms(connection, "conference.push.appaas.com");
	            for (HostedRoom room : rooms) {
	            	if(D) Log.e(TAG, room.getName());
	            	
	            	messages.add(new OneComment(true, room.getName()));
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                		}
                	});
	            	
	            }
	            */

	            result = "OK";
	            
	            //setConnection(connection);
	            
	            
	            
	        } catch (XMPPException ex) {
	            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
	            Log.e("XMPPClient", ex.toString());
	            
	            result = "FAIL";
	            
	            //setConnection(null);
	        }
	        
	        dialog.dismiss();
	        
	        
	        if (result.equals("OK"))
	        {
	        	/*
	        	Intent in = new Intent(getBaseContext(), Welcome1.class);
				in.putExtra("UserName", username);
				startActivity(in);
				*/
	        	
	        	
				Intent in = new Intent(getBaseContext(), MainActivity.class);
				in.putExtra("UserName", username);
				startActivity(in);
				
	        }
	        else
	        {
	        	//Toast.makeText(getApplicationContext(), "User Name and Password miss match..\nPlease Try Again", Toast.LENGTH_LONG).show();
	    		//Intent intent = new Intent(getBaseContext(), LoginActivity.class);
	    		//startActivity(intent);
	        }
	        
    		return result;
    	}
    	
    	/*
    	@Override
        protected void onPostExecute(String result) {
    		
    		dialog.dismiss();
    	}
    	*/
    	
    }
    
    
    
    
}
